package com.googlecode.imanager.client.value.el;

import com.googlecode.imanager.client.report.Field;
import com.googlecode.imanager.client.util.HasText;
import com.googlecode.imanager.client.value.HasValue;
import com.googlecode.imanager.client.value.ValueType;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class Reference extends Expression {

    private static final long serialVersionUID = 1L;

    private final Object value;
    private final ValueType type;
    
    public Reference(HasText value) {
        if (value == null){
            this.value = "";
        } else {
            this.value = value;
        }
        this.type = ValueType.TEXT;
    }
    
    public Reference(HasValue value) {
        this.value = value;
        this.type = ValueType.DEFAULT;
    }
    
    public Reference(Field<?> value) {
        this.value = value;
        this.type = ValueType.DEFAULT;
    }
    
    public final Object getSource(){
        return value;
    }
    
    @Override
    public ValueType getValueType() {
        return type;
    }

    @Override
    public Object getValue() {
        Object result = this.value;
        
        switch (type) {
            case TEXT:
                if (value instanceof HasText){
                    String text = ((HasText) value).getText();
                    result = (text == null ? "" : text);
                }
                break;
                
            case DEFAULT:
                if (value instanceof HasValue){
                    result = ((HasValue) value).getValue();

                    if (result == null){
                        if (value instanceof HasText){
                            String text = ((HasText) value).getText();
                            result = (text == null ? "" : text);
                        }
                    }
                }                
            default:
                break;
        }
        
        return result;
    }

    @Override
    public Expression[] getSubExpressions() {
        return EMPTY_EXPRESSION_ARRAY;
    }

}
